package com.fingard.dsp.bank.directbank.citic04.util;

import org.apache.commons.lang.ArrayUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.*;
import java.security.*;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;


public class RSAUtil {
    public static final String KEY_ALGORITHM = "RSA";
    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
    public static final String CHARSET = "GB18030";
    /**
     * 字节数据转字符串专用集合
     */
    private static final char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /**
     * 公钥文件PEM编码
     *
     * @param in 公钥输入流
     * @throws Exception 加载公钥时产生的异常
     */
    public static RSAPublicKey loadPublicKey(InputStream in) throws Exception {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String readLine = null;
            StringBuilder sb = new StringBuilder();
            while ((readLine = br.readLine()) != null) {
                if (readLine.charAt(0) == '-') {
                    continue;
                } else {
                    sb.append(readLine);
                    sb.append('\r');
                }
            }
            return loadPublicKey(sb.toString());
        } catch (IOException e) {
            throw new Exception("公钥数据流读取错误");
        } catch (NullPointerException e) {
            throw new Exception("公钥输入流为空");
        }
    }

    /**
     * 从字符串中加载公钥
     *
     * @param publicKeyStr 公钥数据字符串
     * @throws Exception 加载公钥时产生的异常
     */
    public static RSAPublicKey loadPublicKey(String publicKeyStr) throws Exception {
        try {
            BASE64Decoder base64Decoder = new BASE64Decoder();
            byte[] buffer = base64Decoder.decodeBuffer(publicKeyStr);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
            return (RSAPublicKey) keyFactory.generatePublic(keySpec);
//			this.publicKey= (RSAPublicKey) keyFactory.generatePublic(keySpec);
//			this._strPublicKey = this.getStringPublicKey();
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此算法");
        } catch (InvalidKeySpecException e) {
            throw new Exception("公钥非法");
        } catch (IOException e) {
            throw new Exception("公钥数据内容读取错误");
        } catch (NullPointerException e) {
            throw new Exception("公钥数据为空");
        }
    }

    /**
     * x.509公钥证书
     *
     * @param certificateFile
     * @throws Exception
     */
    public static RSAPublicKey generatePublicKeyX509(String certificateFile) throws Exception {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        FileInputStream fs = new FileInputStream(certificateFile);
        X509Certificate x = (X509Certificate) cf.generateCertificate(fs);
        PublicKey pk = x.getPublicKey();
        return (RSAPublicKey) pk;
//		this._strPublicKey = this.getStringPublicKey();
    }

    /**
     * 从文件中加载私钥
     *
     * @return 是否成功
     * @throws Exception
     */
    public static RSAPrivateKey loadPrivateKey(InputStream in) throws Exception {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String readLine = null;
            StringBuilder sb = new StringBuilder();
            while ((readLine = br.readLine()) != null) {
                if (readLine.charAt(0) == '-') {
                    continue;
                } else {
                    sb.append(readLine);
                    sb.append('\r');
                }
            }
            return loadPrivateKey(sb.toString());
        } catch (IOException e) {
            throw new Exception("私钥数据读取错误");
        } catch (NullPointerException e) {
            throw new Exception("私钥输入流为空");
        }
    }

    public static RSAPrivateKey loadPrivateKey(String privateKeyStr) throws Exception {
        try {
            BASE64Decoder base64Decoder = new BASE64Decoder();
            byte[] buffer = base64Decoder.decodeBuffer(privateKeyStr);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
//			this.privateKey= (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
//			this._strPrivateKey = this.getStringPrivateKey();
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此算法");
        } catch (InvalidKeySpecException e) {
            throw new Exception("私钥非法");
        } catch (IOException e) {
            throw new Exception("私钥数据内容读取错误");
        } catch (NullPointerException e) {
            throw new Exception("私钥数据为空");
        }
    }

    public static String getStringPublicKey(RSAPublicKey publicKey) {
        byte[] bts = publicKey.getEncoded();
        BASE64Encoder ecode = new BASE64Encoder();
        return ecode.encodeBuffer(bts);
    }

    public static String getStringPrivateKey(RSAPrivateKey privateKey) {
        byte[] bts = privateKey.getEncoded();
        BASE64Encoder ecode = new BASE64Encoder();
        return ecode.encodeBuffer(bts);
    }

    public static String encrypt(RSAPublicKey publicKey, String orgmsg, String charset) throws Exception {
        return encrypt(publicKey, orgmsg.getBytes(charset));
    }

    /**
     * 公钥加密过程
     *
     * @param publicKey     公钥
     * @param plainTextData 明文数据
     * @return
     * @throws Exception 加密过程中的异常信息
     */
    public static String encrypt(RSAPublicKey publicKey, byte[] plainTextData) throws Exception {
        if (publicKey == null) {
            throw new Exception("加密公钥为空, 请设置");
        }
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);

            //超过117字节报错，分段加密
            byte[] enbyte = null;
//			StringBuilder sb=new StringBuilder();
            for (int i = 0; i < plainTextData.length; i += 64) {

                byte[] output = cipher.doFinal(ArrayUtils.subarray(plainTextData, i, i + 64));
                enbyte = ArrayUtils.addAll(enbyte, output);
            }

            BASE64Encoder encode = new BASE64Encoder();
            return encode.encodeBuffer(enbyte);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此加密算法");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        } catch (InvalidKeyException e) {
            throw new Exception("加密公钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
            throw new Exception("明文长度非法");
        } catch (BadPaddingException e) {
            throw new Exception("明文数据已损坏");
        }
    }

    public static String decrypt(RSAPrivateKey privateKey, String codeCipherData, String charset) throws Exception {
        byte[] en = decrypt(privateKey, codeCipherData);
        return new String(en, charset);
    }

    /**
     * 私钥解密过程
     *
     * @param privateKey 私钥
     * @return 明文
     * @throws Exception 解密过程中的异常信息
     */
    public static byte[] decrypt(RSAPrivateKey privateKey, String codeCipherData) throws Exception {
        if (privateKey == null) {
            throw new Exception("解密私钥为空, 请设置");
        }
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            BASE64Decoder decode = new BASE64Decoder();
            //分段解密
            byte[] debyte = null;
            byte[] data = decode.decodeBuffer(codeCipherData);
            for (int i = 0; i < data.length; i += 128) {
                byte[] output = cipher.doFinal(ArrayUtils.subarray(data, i, i + 128));
                debyte = ArrayUtils.addAll(debyte, output);
            }

            return debyte;
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此解密算法");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        } catch (InvalidKeyException e) {
            e.printStackTrace();
            throw new Exception("解密私钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
            throw new Exception("密文长度非法");
        } catch (BadPaddingException e) {
            e.printStackTrace();
            throw new Exception("密文数据已损坏");
        }
    }

    public static String byteArrayToCode(byte[] data) {
        BASE64Encoder encode = new BASE64Encoder();
        return encode.encodeBuffer(data);
    }

    public static byte[] codeToByteArray(String data) throws IOException {
        BASE64Decoder decode = new BASE64Decoder();
        return decode.decodeBuffer(data);
    }

    /**
     * 字节数据转十六进制字符串
     *
     * @param data 输入数据
     * @return 十六进制内容
     */
    public static String byteArrayToString(byte[] data) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < data.length; i++) {
            //取出字节的高四位 作为索引得到相应的十六进制标识符 注意无符号右移
            stringBuilder.append(HEX_CHAR[(data[i] & 0xf0) >>> 4]);
            //取出字节的低四位 作为索引得到相应的十六进制标识符
            stringBuilder.append(HEX_CHAR[(data[i] & 0x0f)]);
            if (i < data.length - 1) {
                stringBuilder.append(' ');
            }
        }
        return stringBuilder.toString();
    }

    /**
     * 签名
     *
     * @param data
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static String sign(String data, String privateKey) {
        try {
            byte[] keyBytes = decode64(privateKey);
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            signature.initSign(privateK);
            signature.update(data.getBytes(CHARSET));
            BASE64Encoder encode = new BASE64Encoder();
            return encode.encodeBuffer(signature.sign());
//		        return encode(signature.sign());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("签名失败");
        }
    }

    public static String sign(RSAPrivateKey privKey, String data) throws Exception {
        try {
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            signature.initSign(privKey);
            signature.update(data.getBytes(CHARSET));
            BASE64Encoder encode = new BASE64Encoder();
            return encode.encodeBuffer(signature.sign());
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("签名失败");
        }
    }

    public static String sign(RSAPrivateKey privKey, String data, String charset) throws Exception {
        return sign(privKey, data.getBytes(charset));
    }

    public static String sign(RSAPrivateKey privKey, byte[] data) throws Exception {
        try {
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            signature.initSign(privKey);
            signature.update(data);
            BASE64Encoder encode = new BASE64Encoder();
            return encode.encodeBuffer(signature.sign());
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("签名失败");
        }
    }

    /**
     * 验证
     *
     * @param data
     * @param publicKey
     * @param sign
     * @return
     * @throws Exception
     */
    public static boolean verify(String data, String publicKey, String sign) {
        try {
            byte[] keyBytes = decode64(publicKey);
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            PublicKey publicK = keyFactory.generatePublic(keySpec);
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            signature.initVerify(publicK);
            signature.update(data.getBytes(CHARSET));
            return signature.verify(decode64(sign));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("验证签名失败");
        }
    }

    public static boolean verify(RSAPublicKey pk, String data, String sign, String charset) {
        try {
            return verify(pk, data.getBytes(charset), sign);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("验证签名失败");
        }
    }

    public static boolean verify(RSAPublicKey pk, byte[] data, String sign) {
        try {
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            signature.initVerify(pk);
            signature.update(data);
            return signature.verify(decode64(sign));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("验证签名失败");
        }
    }

    public static boolean verify(RSAPublicKey pk, String data, String sign) {
        try {
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            signature.initVerify(pk);
            signature.update(data.getBytes(CHARSET));
            return signature.verify(decode64(sign));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("验证签名失败");
        }
    }

    public static byte[] decode64(String base64) throws Exception {
        BASE64Decoder decoder = new BASE64Decoder();
        return decoder.decodeBuffer(base64);
    }

    public static String encode64(byte[] bytes) throws Exception {
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encodeBuffer(bytes);
    }

}
